package com.java.simple.study.jvm.gc.systemgc;

import com.java.simple.study.tool.Sleeper;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zhoujunlin
 * @date 2022年11月07日 17:33
 * @desc 感受stw的存在
 */
public class StopTheWorldDemo {

    public static class WordThread extends Thread {
        List<byte[]> list = new ArrayList<>();

        @Override
        public void run() {
            try {
                while (true) {
                    // 存放1000个 1k
                    for (int i = 0; i < 1000; i++) {
                        byte[] buffer = new byte[1024];
                        list.add(buffer);
                    }
                    // 大于10M回收
                    if (list.size() > 10000) {
                        list.clear();
                        // 会触发full gc 进而会出现stw事件
                        System.gc();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static class PrintThread extends Thread {
        public final long startTime = System.currentTimeMillis();

        @Override
        public void run() {
            try {
                while (true) {
                    long t = System.currentTimeMillis() - startTime;
                    System.out.println(t / 1000 + "." + t % 1000);
                    Sleeper.sleep(1);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        WordThread wordThread = new WordThread();
        PrintThread printThread = new PrintThread();

        wordThread.start();
        printThread.start();
    }

}
